﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sita.Presentation.ViewModels;
using System.Web.Security;

using Sita;
using Sita.MainModule.Services;
using Sita.Entities;
using Sita.Presentation.Models;

namespace Sita.Presentation.Controllers
{
    public class AccountController : DefaultController
    {
        UserService UserService;

        public AccountController()
        {
            UserService = new UserService();
        }

        [HttpGet]
        public ActionResult LogOn()
        {
            return View(new LogOnModel() { Username="kcarpintero" });
        }

        [HttpPost]
        public JsonResult LogOn(LogOnModel logOn)
        {
            JsonResult Result;
            User UserData;
            string AuthUrl;
            ModuleService ModuleService = new ModuleService();


            UserData = UserService.GetUserByUserName(logOn.Username);


            if (UserData != null)
            {
                if (UserData.Blocked)
                {
                    logOn.ErrorMessage = Resources.Account.LogOn.UserIsBlocked;
                    logOn.Result = false;
                }
                else
                {
                    if (String.Compare(UserData.Password, logOn.Password, false) == 0)
                    {
                        UserData.AccessNumber = 0;
                        UserData.LastAccess = DateTime.Now;
                        UserService.ModifyUser(UserData);

                        System.Globalization.CultureInfo UserSpecificCulture = System.Globalization.CultureInfo.CreateSpecificCulture(UserData.Culture);

                        System.Threading.Thread.CurrentThread.CurrentCulture = UserSpecificCulture;
                        System.Threading.Thread.CurrentThread.CurrentUICulture = UserSpecificCulture;

                        TimeSpan HoursDifference = new TimeSpan();

                        //HoursDifference = HoursDifference.GetHoursDifference(DateTime.Now, UserData.TimeZone, UserData.DaylightSavingTime);

                        UserSession UserSession = new UserSession(UserData,
                                                                  UserService.GetUserPermissions(UserData.UserID),
                                                                  DateTime.Now,
                                                                  UserService.GetUserBusinessUnits(UserData.UserID),
                                                                  HoursDifference,
                                                                  ModuleService.GetModulesWithUserPermissionsByUserID(UserData.UserID)
                                                                  );

                        Session.Add("Account.UserSession", UserSession);

                        //FormsAuthentication.SetAuthCookie(UserData.UserID + ":::" + UserData.Username, false);

                        if (!UserData.ModifiedPasswordDate.HasValue)
                        {
                            UserData.ModifiedPasswordDate = DateTime.MinValue;
                        }



                        //HomeBusinessID = m_UserService.GetUserHomeBusinessId(UserData.UserID);
                        //if (HomeBusinessID > 0)
                        //{
                        //    UserSession.CurrentBusinessID = HomeBusinessID;
                        //}
                        UserSession.CurrentBusinessID = UserData.BusinessUnitID;

                        //HomePageCode = m_UserService.GetUserHomePageCode(UserData.UserID);
                        //if ("HOME".Equals(HomePageCode))
                        //{
                        //    logOn.HomePage = "Finder/Index";

                        //}
                        //else
                        //{
                        //    if (ModuleBusinessService.FindByModuleCodeAndBusinessID(HomePageCode, UserSession.CurrentBusinessID))
                        //    {
                        //        var CurrentModule = ModuleService.GetModuleByCode(HomePageCode);
                        //        logOn.HomePage = CurrentModule.TargetController + "/" + CurrentModule.TargetAction;
                        //    }
                        //    else
                        //    {
                        //        logOn.HomePage = "Finder/Index";
                        //    }
                        //}

                        logOn.HomePage = "Dashboard/Index";

                        if (DateTime.Now - UserData.ModifiedPasswordDate.Value > new TimeSpan(90, 0, 0, 0, 0))
                        {
                            AuthUrl = Url.Content("~");
                            logOn.AuthenticatedUrl = AuthUrl;
                            logOn.MustChangePassword = true;
                            logOn.Result = true;
                        }
                        else
                        {
                            logOn.MustChangePassword = false;
                            //AuthUrl = Response.ApplyAppPathModifier("/");

                            AuthUrl = Url.Content("~");

                            logOn.AuthenticatedUrl = AuthUrl;
                            logOn.Result = true;
                        }


                    }
                    else
                    {
                        logOn.Result = false;
                        UserData.AccessNumber++;
                        if (UserData.AccessNumber == 3)
                        {
                            UserData.Blocked = true;
                            logOn.ErrorMessage = Resources.Account.LogOn.UserIsBlocked;
                        }
                        else
                        {
                            logOn.ErrorMessage = Resources.Account.LogOn.InvalidUsernamePassword;
                        }
                        UserService.ModifyUser(UserData);
                    }
                }
            }
            else
            {
                logOn.ErrorMessage = Resources.Account.LogOn.InvalidUsernamePassword;
                logOn.Result = false;
            }


            Result = new JsonResult();
            Result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            Result.Data = logOn;

            Session["KeepSessionAlive"] = DateTime.Now;

            return Json(Result);
        }

        [HttpGet]
        public ActionResult LogOff(LogOnModel logOn)
        {
            Session.Remove("Account.UserSession");
            FormsAuthentication.SignOut();
            Session.Abandon();
            return RedirectToAction("LogOn", "Account");
        }
    }
}
